package gek.uni.aspirant.uml.utils;

import gek.uni.aspirant.ocl.parser.ocl2tree.parser.OclInvariantToPrologParser;
import gek.uni.aspirant.ocl.types.prolog.CodeGeneratorPair;
import gek.uni.aspirant.ocl.types.prolog.PrologGeneratorResult;
import gek.uni.aspirant.prolog.utils.pl2.PrologSystemUtils;

import java.util.List;
import java.util.Hashtable;

import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Element;

import java.util.Map;
import org.eclipse.ocl.expressions.OCLExpression;

public class OclUtils {

  /**
   * Вызывает правильный обработчик ocl-выражения и элемента модели
   * 
   * @param context
   * @param expressions
   * @return
   * @throws Exception
   */
  public static PrologGeneratorResult processUmlOclExpression(Element context,
      List<String> expressions) throws Exception {
    if (expressions.size() == 0)
      return null;

    if (context instanceof Classifier) {
      OclInvariantToPrologParser parser = new OclInvariantToPrologParser(
          (Classifier) context, expressions.get(0));
      PrologGeneratorResult result = parser.parse();

      CodeGeneratorPair codeGeneratorPair = result.getCodeGeneratorPair();
//      String resultVarName = codeGeneratorPair.getResultVarName();
      StringBuilder newResultBldr = new StringBuilder();
      if ((codeGeneratorPair.getCode()!="")&&(codeGeneratorPair.getResultVarName()!="")) {
    	  newResultBldr.append(codeGeneratorPair.getResultVarName());
    	  newResultBldr.append("=true, ");
    	  newResultBldr.append(codeGeneratorPair.getCode());
   		  newResultBldr.replace(newResultBldr.length()-2, 
			  newResultBldr.length()-1, ".");
      }
      codeGeneratorPair.setCode(newResultBldr.toString());
      
      String clpfdlibPath = System.getenv("CLPFD_LIB_PATH");
      String oclurlibPath = System.getenv("OCLUR_LIB_PATH");      
      boolean clpfdSucceeded = PrologSystemUtils.consultData(clpfdlibPath);
      boolean oclurSucceeded = PrologSystemUtils.consultData(oclurlibPath);
      
      String query = result.getCodeGeneratorPair().getCode();
      Map<String,OCLExpression> variablesMap = result.getEssentialMap();      
      Hashtable[] prologSolutions = PrologSystemUtils.exequteQuery(query, 
    		  variablesMap);
      
      boolean solutionFromJPLExists = (prologSolutions.length>0);      
      if (solutionFromJPLExists) {
    	  Hashtable solutionToParse = prologSolutions[0];
    	  PrologSystemUtils.parsePrologSolution(solutionToParse, variablesMap);
      }

      
      
      
      //PrologSystemUtils.domXmlExample();
	      
      return result;
    }
    return null;
  }
}
